package com.cbtx.networklib.ssl

import android.util.Log
import java.security.*
import java.security.cert.CertificateException
import java.security.cert.CertificateExpiredException
import java.security.cert.CertificateNotYetValidException
import java.security.cert.X509Certificate
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

/**
 * author : joker.peng
 * e-mail : joker@fiture.com
 * date   : 2021/6/29 1:05 PM
 * desc   :
 */
object SSLManager {

    private const val TAG = "SSLManager"

    /**
     * 获取 SSLSocketFactory
     */
    @Throws(RuntimeException::class)
    @JvmStatic
    fun getSSLSocketFactory(): SSLSocketFactory {
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, getTrustManager(), SecureRandom())
        return sslContext.socketFactory
    }

    /**
     * 获取 TrustManager
     */
    private fun getTrustManager(): Array<TrustManager> {
        return arrayOf(object : X509TrustManager {
            override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
            }

            @Throws(CertificateException::class)
            override fun checkServerTrusted(chain: Array<X509Certificate>?, authType: String) {
                if (chain != null) {
                    for (cert in chain) {
                        try {
                            // 验证证书是否有效
                            cert.checkValidity()
                        } catch (e: CertificateExpiredException) {
                            //此异常是证书已经过期异常，在手机调到证书生效时间之后会捕捉到此异常
                            Log.e(
                                TAG,
                                "checkServerTrusted: CertificateExpiredException:"
                                        + e.localizedMessage
                            )
                        } catch (e: CertificateNotYetValidException) {
                            //此异常是证书未生效异常，在手机调到证书生效时间之前会捕捉到此异常
                            Log.e(
                                TAG,
                                "checkServerTrusted: CertificateNotYetValidException:"
                                        + e.localizedMessage
                            )
                        }

                        try {
                            // 验证密钥
                            cert.verify(cert.publicKey)
                        } catch (e: CertificateExpiredException) {
                            //此异常是证书已经过期异常，在手机调到证书生效时间之后会捕捉到此异常
                            Log.e(
                                TAG,
                                "checkServerTrusted: CertificateExpiredException:"
                                        + e.localizedMessage
                            )
                        } catch (e: CertificateNotYetValidException) {
                            //此异常是证书未生效异常，在手机调到证书生效时间之前会捕捉到此异常
                            Log.e(
                                TAG,
                                "checkServerTrusted: CertificateNotYetValidException:"
                                        + e.localizedMessage
                            )
                        } catch (ex: CertificateException) {
                            //其他异常正常报错
                            Log.e(
                                TAG, "Throw checkClientTrusted: "
                                        + ex.localizedMessage
                            )
                            throw ex
                        } catch (e: NoSuchAlgorithmException) {
                            Log.e(
                                TAG,
                                "checkServerTrusted: NoSuchAlgorithmException:"
                                        + e.localizedMessage
                            )
                        } catch (e: InvalidKeyException) {
                            Log.e(
                                TAG,
                                "checkServerTrusted: InvalidKeyException:"
                                        + e.localizedMessage
                            )
                        } catch (e: NoSuchProviderException) {
                            Log.e(
                                TAG,
                                "checkServerTrusted: NoSuchProviderException:"
                                        + e.localizedMessage
                            )
                        } catch (e: SignatureException) {
                            Log.e(
                                TAG,
                                "checkServerTrusted: SignatureException:"
                                        + e.localizedMessage
                            )
                        }
                    }
                }
            }

            override fun getAcceptedIssuers(): Array<X509Certificate> {
                return arrayOf()
            }
        })
    }
}
